import {
	ref
} from 'vue'
import {
	defineStore
} from 'pinia'
import {
	port,
	imgUrl
} from '/service/port'

const updateScssVariables = (config) => {

	// #ifdef H5
	const style = document.documentElement.style
	style.setProperty('--theme-color', config.themeColor)
	style.setProperty('--theme-bg-color', config.themeBgColor)
	style.setProperty('--theme-text-color', config.themeTextColor)
	style.setProperty('--theme-bg-btn-color', config.themeBgBtnColor)
	style.setProperty('--theme-btn-box-shadow', config.themeBtnBoxShadow)
	style.setProperty('--theme-bk-bg-color', config.themeBkBgColor)
	style.setProperty('--theme-light-color', config.themeLightColor)
	style.setProperty('--theme-gradient-color', config.themeGradientColor)
	style.setProperty('--theme-bg-gradient-color', config.themeBgGradientColor)
	style.setProperty('--theme-bg-gradient-color-vertical', config.themeBgGradientColorVertical)
	// #endif
}


export const useThemeStore = defineStore('theme', {
	state: () => ({
		init: false,
		//主题色
		themeColor: '',
		//页面背景底色
		themeBgColor: '',
		//按钮颜色;
		themeBgBtnColor: '',
		//按钮阴影
		themeBtnBoxShadow: '',
		//默认文字颜色
		themeTextColor: '',
		//首页爆款文字颜色
		themeBkBgColor: '',
		//主题色浅色
		themeLightColor: '',
		//主题色渐变
		themeGradientColor: '',
		//主题色背景辅助色渐变
		themeBgGradientColor: '',
		//主题色背景辅助色渐变2
		themeBgGradientColorVertical: '',
		//各种背景图
		bg: {}
	}),
	actions: {
		async fetchThemeConfig() {
			if (this.init) return;
			const e = await port('getTheme')
			Object.keys(e.data.color).forEach((v) => {
				this[v] = e.data.color[v]
			})

			Object.keys(e.data.bg).forEach((v) => {
				this.bg[v] = imgUrl + e.data.bg[v]
			});
			updateScssVariables(e.data.color)

			if (typeof uni.setTabBarStyle === 'function') {
				uni.setTabBarStyle(e.data.tabBar)

				e.data.tabBar.list.forEach((v, i) => {
					uni.setTabBarItem({
						index: i,
						...v
					})
				})
				this.init = true;
			}

		}
	}

})